package fr.cephb.lexyacc;

/** class implementing the comparaison e.g. lower than equals, not-equals, etc...*/
public class CompareNode extends YNode
	{
	private CompareOp op;
	/** constructire with the two nodes to compare and the comparator */
	public CompareNode(Node left,CompareOp op,Node right)
		{
		super(left,right);
		this.op=op;
		}
	
	/** get the comparator operator */
	public CompareOp getOp()
		{
		return this.op;
		}
	/** compare the two values of the child nodes. The nodes' values should have the same class*/
	@SuppressWarnings("unchecked")
	@Override
	public Object eval(Context ctx) {
		Object o1= at(0).eval(ctx);
		if(o1 ==null || !(o1 instanceof Comparable<?>)) return null;
		Object o2= at(1).eval(ctx);
		if(o2 ==null || !(o2 instanceof Comparable<?>)) return null;
		
		if(o1.getClass()!=o2.getClass()) return null;
		Comparable<Object> c1= Comparable.class.cast(o1);
		Comparable<Object> c2= Comparable.class.cast(o2);
		int i= c1.compareTo(c2);
		switch(this.op)
			{
			case EQ: return i==0;
			case NE: return i!=0;
			case LT: return i<0;
			case LE: return i<=0;
			case GT: return i>0;
			case GE: return i>=0;
			}
		throw new IllegalArgumentException(String.valueOf(this.op));
	}

	@Override
	public String getName() {
		return getOp().name();
		}

}



